package com.nwu.api.config;


import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;

public class DefaultFeignConfig {//默认配置，需要在客户端应用
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }//日志级别
    @Bean
    public RequestInterceptor userInfoRequestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //获取登录用户
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                Long id = (Long) authentication.getPrincipal();
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                String authoritiesString = authorities.toString();//todo 调试远程调用的格式
                if(id == null) {
                    // 如果为空则直接跳过
                    return;
                }
                // 如果不为空则放入请求头中，传递给下游微服务
                requestTemplate.header("user-info",id.toString()).header("menus",authoritiesString);
            }
        };
    }

}
